package com.goldplusgold.tradedelay.app.trade.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.activity.BaseActivity;
import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.support.lib.widget.recyclerview.RecyclerViewExtended;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.tradedelay.app.market.eventbus.DynaMessageEvent;
import com.goldplusgold.tradedelay.app.market.eventbus.SltpNotificationMessageEvent;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.network.lib.http.netty.ChannelManager;
import com.goldplusgold.network.lib.http.protobuf.Market;
import com.goldplusgold.tradedelay.app.trade.adapter.ProfitAndLossAdapter;
import com.goldplusgold.tradedelay.app.trade.dialog.DeleteWarmTipDialog;
import com.goldplusgold.tradedelay.app.trade.dialog.SaveDialog;
import com.goldplusgold.tradedelay.app.trade.dialog.UpdateDialog;
import com.goldplusgold.tradedelay.app.trade.dialog.WarmTipDialog;
import com.goldplusgold.tradedelay.app.trade.networkservice.TradeService;
import com.goldplusgold.tradedelay.app.trade.pojo.ProfitAndLoss;
import com.goldplusgold.tradedelay.app.trade.pojo.TriggeredRecord;
import com.goldplusgold.tradedelay.app.trade.pojo.TriggeredRecordList;
import com.goldplusgold.support.lib.utils.DateFormatUtils;
import com.goldplusgold.support.lib.utils.NetWorkConstant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * Created by Administrator on 2017/5/25.
 */

public class ProfitAndLossActivity extends BaseActivity implements View.OnClickListener, Handler.Callback {


    public PopupWindow window;

    public RecyclerViewExtended recyclerView;
    public ProfitAndLossAdapter adapter;

    public RelativeLayout addProfitItem;
    public RelativeLayout addLossItem;

    public LinearLayoutManager layoutManager;
    public TextView mBearbullType;
    public TextView mLastedPrice;
    public TextView mTextViewHarden;
    public TextView triggerList;
    public ImageView iv_back;
    public TextView tv_title;
    public View operationStatePrompt;

    private TextView operationStatePromptText;
    private ImageView operationState;
    private ImageView operationStatePromptClose;
    private TextView mTextViewOpenAvgPrice;
    private TextView mTextViewNotice;
    private TextView mTextViewLimit;

    //
    private String prodCode;
    private String bearbullType;
    private int lots;
    private TextView mInstType;
    private int openAvgPrice;

    private Handler handler = new Handler(this);

    public static final String FROM_PAGE_NAME = "profit_loss_page";

    @Override
    public int getLayoutId() {
        return R.layout.activity_profit_loss;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //接收下单页面传过来的值
        Intent intent = getIntent();
        if (intent != null) {
            String code = intent.getStringExtra("prodCode");
            if (!TextUtils.isEmpty(code)) {
                switch (code) {
                    case "Au(T+D)":
                        prodCode = "AU";
                        break;
                    case "mAu(T+D)":
                        prodCode = "MAU";
                        break;
                    case "Ag(T+D)":
                        prodCode = "AG";
                        break;
                }

            }

            String type = intent.getStringExtra("bearbullType");
            if (!TextUtils.isEmpty(type)) {
                switch (type) {
                    case "多":
                        bearbullType = "BULL";
                        break;
                    case "空":
                        bearbullType = "BEAR";
                        break;
                }
            }
            lots = intent.getIntExtra("lots", 0);
            openAvgPrice = intent.getIntExtra("openAvgPrice", 0);
        }
//        showPopupWindow();
        initMarket();
        initAdapter();
        testDataAdapter();
    }


    private void testData() {
        prodCode = "Au(T+D)";//Ag(T+D) Au(T+D) mAu(T+D)
        bearbullType = "多";//多 空
        lots = 3;
        openAvgPrice = 285;
    }


    private void testDataAdapter() {
        // time_ = "";
        //openPrice_ = "";
        //upDown_ = "";
        //upDownRate_ = "";
        //highestPrice_ = "";
        //lowestPrice_ = "";
        //lastPrice_ = "";
        //lastClose_ = "";
        //lastSettle_ = "";
        //volume_ = 0L;
        Market.QuoteDyna quoteDyna = Market.QuoteDyna.newBuilder()
                .setTime("20170617")
                .setOpenPrice("273.45")
                .setUpDown("+")
                .setUpDownRate("20")
                .setHighestPrice("291.50")
                .setLowestPrice("267.10")
                .setLastPrice("286.50")
                .setLastClose("273.49")
                .setVolume(3L)
                .build();
        adapter.setQuoteDyna(quoteDyna);
        fillMarketData(quoteDyna);
    }

    public void initAdapter() {
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        //设置Item增加、移除动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new ProfitAndLossAdapter(this, bearbullType, prodCode, lots);
        recyclerView.setAdapter(adapter);

        View emptyView = LayoutInflater.from(this).inflate(R.layout.item_no_list, null);
        recyclerView.setEmptyView(emptyView);
    }


    @Override
    protected void initView() {
        super.initView();
        //title
        iv_back = (ImageView) findViewById(R.id.iv_back);
        tv_title = (TextView) findViewById(R.id.title_txt);
        triggerList = (TextView) findViewById(R.id.txt_right);
        triggerList.setOnClickListener(this);

        //返回提示
        operationStatePrompt = findViewById(R.id.layout_operation_state_prompt);
        operationStatePromptText = (TextView) findViewById(R.id.tv_operation_state);
        operationState = (ImageView) findViewById(R.id.iv_operation_state);
        operationStatePromptClose = (ImageView) findViewById(R.id.iv_operation_state_prompt_cancle);
        operationStatePromptClose.setOnClickListener(this);

        //market
        mInstType = (TextView) findViewById(R.id.id_inst_type_textView);
        mBearbullType = (TextView) findViewById(R.id.tv_bearbullType);
        mLastedPrice = (TextView) findViewById(R.id.tv_lasted_price);
        mTextViewHarden = (TextView) findViewById(R.id.tv_harden);
        mTextViewLimit = (TextView) findViewById(R.id.tv_limit);

        mTextViewOpenAvgPrice = (TextView) findViewById(R.id.tv_openAvgPrice);
        mTextViewOpenAvgPrice.setText(String.valueOf(openAvgPrice));
        //小提示
        mTextViewNotice = (TextView) findViewById(R.id.id_text_view_notice);
        mTextViewNotice.setOnClickListener(this);

        recyclerView = (RecyclerViewExtended) findViewById(R.id.rv_extended);

        addProfitItem = (RelativeLayout) findViewById(R.id.rl_add_profit_list);
        addProfitItem.setOnClickListener(this);
        addLossItem = (RelativeLayout) findViewById(R.id.rl_add_loss_list);
        addLossItem.setOnClickListener(this);

    }

    private void showPopupWindow() {
        if (DateFormatUtils.isInTradeTime(DateFormatUtils.getCurrentDayOfWeek(), DateFormatUtils.getCurrentTime())) { //在交易时间段内
            //判断当天是否是第一次进入此页面
            boolean isFirstRun = AppCacheSharedPreferences.getCacheBoolean("isFirstRun", true);
            if (isFirstRun) {
                AppCacheSharedPreferences.putCacheBoolean("isFirstRun", false);
                //弹风险提示框
                findViewById(R.id.activity_profit_loss).post(new Runnable() {
                    @Override
                    public void run() {
                        showRiskPopupWindow();
                    }
                });
            }
        } else { //如果不在交易时间内，则弹出“已收盘”提示框，点击确定俺就返回“下单”页面；
            findViewById(R.id.activity_profit_loss).post(new Runnable() {
                @Override
                public void run() {
                    showWarmPopupWindow();
                }
            });

        }

    }

    private void initMarket() {
        UserInfo userInfo = MyService.getInstance().getmUserInfo();
        Market.InstType instType = null;
        String mTradeType = "";
        if (!TextUtils.isEmpty(prodCode)) {
            switch (prodCode) {
                case "AU":
                    instType = Market.InstType.AU_TD;
                    mTradeType = "黄金延期Au(T+D)";
                    break;
                case "MAU":
                    instType = Market.InstType.MAU_TD;
                    mTradeType = "迷你黄金延期mAu(T+D)";
                    break;
                case "AG":
                    instType = Market.InstType.AG_TD;
                    mTradeType = "白银延期Ag(T+D)";
                    break;
            }
            mInstType.setText(mTradeType);
        }

        if (userInfo != null && instType != null) {
            sendRequestMsg(instType, userInfo.getUserName());
        }


        if (!TextUtils.isEmpty(bearbullType)) {
            switch (bearbullType) {
                case "BULL":
                    mBearbullType.setText("多头");
                    mBearbullType.setTextColor(getResources().getColor(R.color.color_red));
                    break;
                case "BEAR":
                    mBearbullType.setText("空头");
                    mBearbullType.setTextColor(getResources().getColor(R.color.color_green));
                    break;
            }
        }
        EventBus.getDefault().register(this);
    }


    @Override
    protected void onStart() {
        super.onStart();
        loadDataAction();
        initData();
    }


    public void loadDataAction() {
        new QueryProfitSettings(prodCode, bearbullType).execute(AsyncTask.TYPE_NET);
    }

    /*发送长连接合约请求*/
    private void sendRequestMsg(Market.InstType instType, String goldExpertNo) {
        Market.Identification identification = Market.Identification.newBuilder()
                .setCategory(Market.Category.QUOTEDYNA)
                .setGoldExpertNo(goldExpertNo)
                .setInstType(instType)
                .build();
        Market.Response response = Market.Response.newBuilder().setIdentification(identification).build();
        ChannelManager.sendMessage(0, response, 100175);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQuoteDynaEventBus(DynaMessageEvent event) {
        if (event.getType() == Market.Category.QUOTEDYNA) {
            fillMarketData(event.getQuoteDyna());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSltpNotificationEventBus(SltpNotificationMessageEvent event) {
        Market.SltpNotification sltpNotification = event.getSltpNotification();
        if (sltpNotification != null && TextUtils.equals(sltpNotification.getType(), "0")) {
            if (sltpNotification.getTriggerData() == null) {
                return;
            }
            Market.SltpRecord sltpRecord = sltpNotification.getTriggerData();
            WarmTipDialog warmTipDialog = new WarmTipDialog();
            warmTipDialog.setSltpRecord(sltpRecord);
            if (adapter != null) {
                warmTipDialog.setHaveNoSave(adapter.hasNoSaveItem());
            }
            warmTipDialog.show(getSupportFragmentManager(), warmTipDialog.getClass().getSimpleName());

            //String id, String prodCode, String bearbullType, String sltpType
            TriggeredRecord record = new TriggeredRecord();
            record.setId(sltpRecord.getId());
            record.setProdCode(sltpRecord.getProdCode());
            record.setBearbullType(sltpRecord.getBearbullType());
            record.setSltpType(sltpRecord.getSltpType());
            deleteItem(record);
        }

        if (sltpNotification != null && TextUtils.equals(sltpNotification.getType(), "1")) {
            List<Market.SltpRecord> deleteData = sltpNotification.getDeleteDataList();
            if (deleteData == null || deleteData.isEmpty()) {
                return;
            }

            DeleteWarmTipDialog dialog = DeleteWarmTipDialog.newInstance(prodCode, bearbullType);
            dialog.show(getSupportFragmentManager(), DeleteWarmTipDialog.class.getSimpleName());
            for (Market.SltpRecord sltpRecord1 : deleteData) {
                Market.SltpRecord sltpRecord = sltpRecord1;
                //String id, String prodCode, String bearbullType, String sltpType
                TriggeredRecord record1 = new TriggeredRecord();
                record1.setId(sltpRecord.getId());
                record1.setProdCode(sltpRecord.getProdCode());
                record1.setBearbullType(sltpRecord.getBearbullType());
                record1.setSltpType(sltpRecord.getSltpType());
                deleteItem(record1);
            }
        }
    }

    /*填充动态数据*/
    private void fillMarketData(Market.QuoteDyna quoteDyna) {
        String upDown = quoteDyna.getUpDownRate().substring(0, 1);
        if ("+".equals(upDown)) {
            mLastedPrice.setTextColor(getResources().getColor(R.color.shallow_red));
        } else if ("-".equals(upDown)) {
            mLastedPrice.setTextColor(getResources().getColor(R.color.color_price_down));
        } else {
            mLastedPrice.setTextColor(getResources().getColor(R.color.td_color_gray_two));
        }
        mLastedPrice.setText(quoteDyna.getLastPrice());
        mTextViewHarden.setText("涨停：" + quoteDyna.getHighestPrice());
        mTextViewLimit.setText("跌停：" + quoteDyna.getLowestPrice());
        adapter.setQuoteDyna(quoteDyna);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void initData() {
        triggerList.setVisibility(View.VISIBLE);
        triggerList.setText("触发记录");
        tv_title.setVisibility(View.VISIBLE);
        tv_title.setText("止盈止损");
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        operationStatePrompt.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_add_loss_list:
                if (adapter.hasNoSaveItem()) {
                    displaySaveDialog(this);
                } else if (adapter.getEnableLossLots() == 0) {
                    operationQueryStatePrompt("没有更多可用手数");
                } else {
                    adapter.addLossItem();
                }

                break;
            case R.id.rl_add_profit_list:
                if (adapter.hasNoSaveItem()) {
                    displaySaveDialog(this);
                } else if (adapter.getEnableProfitLots() == 0) {
                    operationQueryStatePrompt("没有更多可用手数");
                } else {
                    adapter.addProfitsItem();
                }

                break;
            case R.id.iv_operation_state_prompt_cancle:
                operationStatePrompt.setVisibility(View.GONE);
                break;
            case R.id.id_text_view_notice:
                mTextViewNotice.setVisibility(View.GONE);
                break;
            case R.id.iv_back:
                if (adapter.hasNoSaveItem()) {
                    displayUpdateDialog(this);
                } else {
                    onBackPressed();
                }
                break;
            case R.id.txt_right:
                if (adapter.hasNoSaveItem()) {
                    displaySaveDialog(this);
                } else {

                    Intent intent = new Intent(this, TriggerListActivity.class);
                    intent.putExtra("fromPage", FROM_PAGE_NAME);
                    startActivity(intent);
                }
                break;
        }
    }


    public void displaySaveDialog(FragmentActivity activity) {
        if (activity == null || activity.isFinishing()) {
            return;
        }

        SaveDialog saveDialog = new SaveDialog();
        saveDialog.show(activity.getSupportFragmentManager(), saveDialog.getClass().getSimpleName());
    }

    public void displayUpdateDialog(FragmentActivity activity) {
        if (activity == null || activity.isFinishing()) {
            return;
        }

        UpdateDialog updateDialog = new UpdateDialog();
        updateDialog.show(activity.getSupportFragmentManager(), updateDialog.getClass().getSimpleName());
    }

    @Override
    public boolean handleMessage(Message msg) {
        int type = msg.what;
        switch (type) {
            case NetWorkConstant.NETWORK_ERROR_CODE:
                showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                break;
            case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                String errorMessage = (String) msg.obj;
                showToastMessage(errorMessage, Toast.LENGTH_LONG);
                break;
        }
        return false;
    }

    public class QueryProfitSettings extends AsyncTask<Void, Void, TriggeredRecordList> {
        public String prodCode;
        public String bearbullType;

        public QueryProfitSettings(String prodCode, String bearbullType) {
            super();
            this.prodCode = prodCode;
            this.bearbullType = bearbullType;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected TriggeredRecordList doInBackground(Void... params) {
            TriggeredRecordList triggeredRecordList = null;
            try {
                triggeredRecordList = TradeService.getInstance().getSettingTriggered(prodCode, bearbullType);
            } catch (ServerException e) {
                e.getMessage();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            if (triggeredRecordList == null) {
                triggeredRecordList = new TriggeredRecordList();
            }
            List<TriggeredRecord> list = triggeredRecordList.getData();
            triggeredRecordList.setData(sortList(list));
            return triggeredRecordList;
        }

        @Override
        protected void onPostExecute(TriggeredRecordList triggeredRecordList) {
            super.onPostExecute(triggeredRecordList);
            dismisLoadingControl();

            if (triggeredRecordList == null) {
                return;
            }
            String code = triggeredRecordList.getCode();
            if (!TextUtils.isEmpty(code)) {
                switch (code) {
                    case "200": //请求查询数据成功
                        List<TriggeredRecord> triggeredRecord = triggeredRecordList.getData();
                        adapter.setArrayList(new ArrayList<>(triggeredRecord));
                        break;
                    case "400":
                    case "410":
                    case "420":
                    case "430":
                    case "440":
                    case "500":
                    default:
                        operationQueryStatePrompt(triggeredRecordList.getMsg());
                        break;
                }
            }
        }


    }


    private List<TriggeredRecord> sortList(List<TriggeredRecord> triggeredRecords) {
        if (triggeredRecords == null || triggeredRecords.isEmpty()) {
            List<TriggeredRecord> triggeredRecordList = new ArrayList<>();
            triggeredRecordList.add(adapter.getProfitEmptyItem());
            triggeredRecordList.add(adapter.getLossEmptyItem());
            return triggeredRecordList;
        }
        List<TriggeredRecord> triggeredRecordList = new ArrayList<>();
        List<TriggeredRecord> stopProfits = new ArrayList<>();
        List<TriggeredRecord> stopLosses = new ArrayList<>();
        for (TriggeredRecord triggeredRecord : triggeredRecords) {
            String sltpType = triggeredRecord.getSltpType();
            if (TextUtils.isEmpty(sltpType)) {
                continue;
            }
            switch (sltpType) {
                case "TP":
                    triggeredRecord.setViewType(ProfitAndLossAdapter.ITEM_PROFIT_NORMAL);
                    stopProfits.add(triggeredRecord);
                    break;
                case "SL":
                    triggeredRecord.setViewType(ProfitAndLossAdapter.ITEM_LOSS_NORMAL);
                    stopLosses.add(triggeredRecord);
                    break;
            }
        }

        if (stopProfits.size() == 0) {
            triggeredRecordList.add(adapter.getProfitEmptyItem());
        } else {
            Collections.sort(stopProfits, new TriggeredRecord());
            //stopProfits
            triggeredRecordList.addAll(stopProfits);
        }

        if (stopLosses.size() == 0) {
            triggeredRecordList.add(adapter.getLossEmptyItem());
        } else {
            Collections.sort(stopLosses, new TriggeredRecord());
            //stopLosses
            triggeredRecordList.addAll(stopLosses);
        }
        return triggeredRecordList;
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if ((window != null) && window.isShowing()) {
            return false;
        }

        return super.dispatchTouchEvent(ev);
    }

    //风险提示
    public void showRiskPopupWindow() {
        window = new PopupWindow(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.risk_warning, null);
        LinearLayout confirm = (LinearLayout) contentView.findViewById(R.id.ll_risk_warning_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
        window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setOutsideTouchable(false);
        window.setFocusable(false);
        window.setBackgroundDrawable(new ColorDrawable(0x90000000));
        window.setContentView(contentView);
        window.showAtLocation(findViewById(R.id.activity_profit_loss), Gravity.CENTER, 0, 0);
    }

    //温馨提示
    public void showWarmPopupWindow() {
        window = new PopupWindow(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.closing_prompt, null);
        LinearLayout confirm = (LinearLayout) contentView.findViewById(R.id.ll_closing_prompt_confirm);
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
                onBackPressed();
            }
        });

        window.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        window.setOutsideTouchable(false);
        window.setFocusable(false);
        window.setBackgroundDrawable(new ColorDrawable(0x90000000));
        window.setContentView(contentView);
        if (window.isShowing()) {
            window.dismiss();
        } else {
            window.showAtLocation(findViewById(R.id.activity_profit_loss), Gravity.CENTER, 0, 0);
        }
    }

    public class DeleteProfitAndLossAsync extends AsyncTask<Void, Void, ProfitAndLoss> {
        private TriggeredRecord record;

        public DeleteProfitAndLossAsync(TriggeredRecord triggeredRecord) {
            super();
            this.record = triggeredRecord;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected ProfitAndLoss doInBackground(Void... params) {
            ProfitAndLoss profitAndLoss = null;
            try {
                if (record != null) {
                    profitAndLoss = TradeService.getInstance().deleteProfitAndLossItem(record.getId(),
                            record.getProdCode(),
                            record.getBearbullType(),
                            record.getSltpType());
                }
            } catch (ServerException e) {
                e.getMessage();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }


            return profitAndLoss;
        }

        @Override
        protected void onPostExecute(ProfitAndLoss profitAndLoss) {
            super.onPostExecute(profitAndLoss);
            if (this == null || isFinishing()) {
                return;
            }

            dismisLoadingControl();
            if (profitAndLoss == null) {
                return;
            }
            responseResultAction(profitAndLoss, "成功删除");
            adapter.addEmptyItem();
        }
    }


    public class UpdateProfitAndLossItemAsync extends AsyncTask<Void, Void, ProfitAndLoss> {
        public String prodCode;
        public String bearbullType;
        public String sltpType;
        public String id;
        String sltpPrice;
        String floatPrice;
        String lots;

        public UpdateProfitAndLossItemAsync(String id, String prodCode, String bearbullType, String sltpType,
                                            String sltpPrice, String floatPrice, String lots) {
            super();
            this.id = id;
            this.prodCode = prodCode;
            this.bearbullType = bearbullType;
            this.sltpType = sltpType;
            this.sltpPrice = sltpPrice;
            this.floatPrice = floatPrice;
            this.lots = lots;

        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected ProfitAndLoss doInBackground(Void... params) {

            try {
                ProfitAndLoss profitAndLoss = TradeService.getInstance().updateProfitAndLossItem(id, prodCode, bearbullType, sltpType, sltpPrice, floatPrice, lots);
                if (profitAndLoss != null) {
                    return profitAndLoss;
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }


            return null;
        }

        @Override
        protected void onPostExecute(ProfitAndLoss profitAndLoss) {
            super.onPostExecute(profitAndLoss);
            if (this == null || isFinishing()) {
                return;
            }

            dismisLoadingControl();
            if (profitAndLoss == null) {
                return;
            }

            responseResultAction(profitAndLoss, "保存成功");
        }
    }


    public class AddProfitAndLossItemAsync extends AsyncTask<Void, Void, ProfitAndLoss> {
        TriggeredRecord triggeredRecord;
        int position;

        public AddProfitAndLossItemAsync(TriggeredRecord triggeredRecord, int position) {
            super();
            this.triggeredRecord = triggeredRecord;
            this.position = position;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected ProfitAndLoss doInBackground(Void... params) {
            ProfitAndLoss profitAndLoss = null;
            try {
                if (triggeredRecord != null) {
                    triggeredRecord.setBearbullType(bearbullType);
                    triggeredRecord.setProdCode(prodCode);
                    profitAndLoss = TradeService.getInstance().addProfitAndLossItem(triggeredRecord.getProdCode(),
                            triggeredRecord.getBearbullType(),
                            triggeredRecord.getSltpType(),
                            triggeredRecord.getSltpPrice(),
                            triggeredRecord.getFloatPrice(),
                            triggeredRecord.getLots());
                }
            } catch (ServerException e) {
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }
            return profitAndLoss;
        }

        @Override
        protected void onPostExecute(ProfitAndLoss profitAndLoss) {
            super.onPostExecute(profitAndLoss);
            if (this == null || isFinishing()) {
                return;
            }

            dismisLoadingControl();
            if (profitAndLoss == null) {
                return;
            }

            responseResultAction(profitAndLoss, "保存成功");
            if (TextUtils.equals(profitAndLoss.getCode(), "200")) {
                TriggeredRecord record = profitAndLoss.getData();
                record.setViewType(triggeredRecord.getViewType());
                adapter.getArrayList().set(position, record);
                adapter.notifyDataSetChanged();
            }
        }

    }

    private void responseResultAction(ProfitAndLoss profitAndLoss, String message) {

        switch (profitAndLoss.getCode()) {
            case "200": //请求添加数据成功, 新增一个normal条目
                operationStatePrompt(message);
                break;
            case "400":
            case "410":
            case "420":
            case "430":
            case "440":
            case "500":
                operationStatePrompt(profitAndLoss.getMsg());
                break;
            default:
                break;
        }


    }


    public void operationStatePrompt(String message) {
        operationStatePrompt.setVisibility(View.VISIBLE);
        operationState.setImageResource(R.drawable.chenggong);
        operationStatePromptText.setText(message);
        operationStatePrompt.postDelayed(new Runnable() {
            @Override
            public void run() {
                operationStatePrompt.setVisibility(View.GONE);
            }
        }, 3000);
    }

    public void operationQueryStatePrompt(String message) {
        operationStatePrompt.setVisibility(View.VISIBLE);
        operationStatePromptText.setText(message);
        operationState.setImageResource(R.drawable.operation_error);
        operationStatePrompt.postDelayed(new Runnable() {
            @Override
            public void run() {
                operationStatePrompt.setVisibility(View.GONE);
            }
        }, 3000);
    }

    public void deleteItem(TriggeredRecord triggeredRecord) {
        //String id, String prodCode, String bearbullType, String sltpType
        new DeleteProfitAndLossAsync(triggeredRecord).execute(AsyncTask.TYPE_NET);
    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

}

